<?php

namespace app\controllers\admin;

use app\models\order\Order;
use app\models\order\OrderItem;
use app\models\order\OrderLogistics;
use app\models\system\SetExpressCompany;
use app\services\Upload as Service;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\IOFactory;

/**
 * Class UploadController
 * @package app\controllers\admin
 */
class UploadController extends \app\controllers\admin\base\AdminController
{
    /**
     * image upload
     *
     * @return \yii\web\Response
     */
    public function actionExecute()
    {
        $bucket = $this->get('bucket');
        $result = Service::uploadImage($bucket);

        if ($result) {
            return $this->success($result, '上传成功');
        } else {
            return $this->fail('上失败,' . Service::getLastError());
        }
    }

    // upload express
    public function actionExpress()
    {
        if (!$_FILES || !$_FILES['file']) {
            return $this->fail('请上传文件');
        }

        $path = $_FILES['file']['tmp_name'];

        $file_name = $_FILES['file']['name'];
        $file_extend = explode('.', $file_name);
        $file_extend = strtolower(end($file_extend));
        if (!in_array($file_extend, ['xls', 'xlsx'])) {
            return $this->fail('文件类型错误');
        }


        $upload_dir_path = \Yii::$app->getBasePath(). '/web/express-excel/';
        $folder_name = date('Ymd');
        $upload_dir = $upload_dir_path . $folder_name;
        if (!file_exists($upload_dir)) {
            mkdir($upload_dir, 0777, true);
            chmod($upload_dir, 0777);
        }

        $hash_key = md5(file_get_contents($path)) . '-' . time();
        $full_name = $folder_name . '/' . $hash_key . '.' . $file_extend;
        $excel = $upload_dir_path . $full_name;
        if (is_uploaded_file($path)) {
            move_uploaded_file($path, $excel);
        } else {
            file_put_contents($excel, file_get_contents($path));
        }

        // read excel
        $reader = IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(true);
        $spread_sheet = $reader->load($excel);
        $word_sheet = $spread_sheet->getActiveSheet();

        // 53行, 列为字母"O", 索引列为 15
        $row = $word_sheet->getHighestRow();
        $column = $word_sheet->getHighestColumn();
        $index = Coordinate::columnIndexFromString($column);

        // var_dump($row, $index);exit;

        // if ($row < 2 || $index < 15) {
        if ($row < 2 || $index < 13) {
            return $this->fail('表格不正确, 请重新导出填写');
        }

        /*
         * array(2) {
              [0]=>
              array(3) {
                ["order_id"]=>
                string(4) "1053"
                ["sn"]=>
                string(19) "2021112005022655581"
                ["express"]=>
                string(15) "YT6144836821280"
              }
              [1]=>
              array(3) {
                ["order_id"]=>
                string(4) "1052"
                ["sn"]=>
                string(19) "2021112001372779605"
                ["express"]=>
                string(0) ""
              }
            }
         */
        $list = [];
        for ($i = 2; $i <= $row; ++$i) {
            $list[] = [
                'order_id' => $word_sheet->getCellByColumnAndRow(1, $i)->getValue(),
                'sn' => $word_sheet->getCellByColumnAndRow(2, $i)->getValue(),
                // 'express' => $word_sheet->getCellByColumnAndRow(15, $i)->getValue(),
                'express' => $word_sheet->getCellByColumnAndRow(13, $i)->getValue(),
                'company' => $word_sheet->getCellByColumnAndRow(14, $i)->getValue(),
            ];
        }

        // var_dump($list);exit;

        // import db
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $result = [];
            foreach ($list as $item) {
                if (!$item['express']) {
                    continue;
                }
                $order = Order::findOne(['id' => $item['order_id']]);
                if (!$order) {
                    continue;
                }
                $order_item = OrderItem::findAll(['order_id' => $order->id]);
                foreach ($order_item as $v) {
                    $logistics = OrderLogistics::findOne(['order_id' => $order->id, 'order_item_id' => $v->id]);
                    if (!$logistics) {
                        $logistics = new OrderLogistics();
                        $logistics->order_id = $order->id;
                        $logistics->order_item_id = $v->id;
                        $logistics->user_address_id = $order->user_address;
                        $logistics->status = 1;

                        // 快递公司编码
                        $x = SetExpressCompany::find()
                            ->where(['code' => $item['company']])
                            ->select(['id'])
                            ->scalar();


                        if ($x) {
                            $logistics->express_company_id = $x;
                        } else {

                            throw new \Exception('快递公司编码请填写完成,或者编码错误');

                            // var_dump($x);exit;
                            // 默认圆通
                            $logistics->express_company_id = 2;
                        }
                    }
                    // $company_flag = preg_replace('/\d+/', '', $item['express']);
                    // // $number = substr($item['express'], strlen($company));
                    //
                    // // $company = SetExpressCompany::findOne(['code' => $company_flag]);
                    // $company = SetExpressCompany::find()
                    //     ->where(['like', 'code', $company_flag])
                    //     ->one();
                    // // var_dump($company);exit;
                    // if (!$company) {
                    //     // continue;
                    // } else {
                    //     $logistics->express_company_id = $company->id;
                    // }

                    $logistics->express_sn = $item['express'];
                    if ($logistics->save()) {
                        $result[] = $logistics;
                    } else {
                        // 注册字段, 可能需要是string
                        // var_dump($logistics->getFirstErrors());exit;
                    }

                    $order->status = Order::$statusMapping['WAIT_RECEIVING'];
                    $order->save();
                }
            }

            $transaction->commit();

            return $this->success($result);

        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }

        return $this->success($result);

    }
}